package com.cheyun.netsalev3.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.databinding.library.baseAdapters.BR
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView


/**
 * 通用适配器
 */
open class MyAdapter(open var layoutId: Int,
                     open var viewModel: Any? = null,
                     open var callback: ItemCallback? = ItemCallback()) :
        ListAdapter<Any, MyAdapter.ViewHolder>(callback!!) {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), layoutId, parent, false))

    }

    override fun onBindViewHolder(holder: MyAdapter.ViewHolder, position: Int) {
        var oldItem = if (position == 0) {
            getItem(position)
        } else {
            getItem(position - 1)
        }
        var param = getItem(position)
        holder.apply {
            bind(param, viewModel, this@MyAdapter.itemCount, oldItem)
            itemView.tag = param
        }

    }


    class ViewHolder(var binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: Any, viewModel: Any?, itemCount: Int, oldItem: Any) {
            binding.apply {
                setVariable(BR.item, item)
                setVariable(BR.viewModel, viewModel)
                setVariable(BR.binding, this)
                setVariable(BR.position, adapterPosition)
                setVariable(BR.isfood, (itemCount - 1) == adapterPosition)
                setVariable(BR.olditem, oldItem)
                executePendingBindings()
            }
        }
    }

    /**
     * 默认的比较器 可以覆盖比较方法
     */
    open class ItemCallback : DiffUtil.ItemCallback<Any>() {
        override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
            return oldItem == newItem
        }

    }


}